import json
import requests

from config.config import settings
from src.auth.auth_manager import auth_manager

class APIManager:
    def __init__(self, client_id, client_secret):
        self.client_id = client_id
        self.client_secret = client_secret

    def create_record(self, object_id, record_data):
        """
        创建记录

        Args:
            object_id (str): 对象ID
            record_data (dict or str): 记录数据，可以是字典或JSON字符串

        Returns:
            dict: 创建的记录数据或None
        """
        token = auth_manager.get_token()
        url = f"{settings.CURD_BASE_URL}/{object_id}/records"
        headers = {"Authorization": token, "Content-Type": "application/json"}
        if not isinstance(record_data, dict):
            record_data = json.loads(record_data)
        data = {"record": record_data}

        try:
            response = requests.post(url, headers=headers, json=data)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"创建记录失败: {e}")
            return None

    def update_record(self, object_id, record_id, record_data):
        """
        更新记录
        
        Args:
            object_id (str): 对象ID
            record_id (str): 记录ID
            record_data (dict or str): 更新的记录数据，可以是字典或JSON字符串
        Returns:
            dict: 更新后的记录数据或None
        """
        token = auth_manager.get_token()
        url = f"{settings.CURD_BASE_URL}/{object_id}/records/{record_id}"
        headers = {"Authorization": token, "Content-Type": "application/json"}
        if not isinstance(record_data, dict):
            record_data = json.loads(record_data)
        data = {"record": record_data}

        try:
            response = requests.patch(url, headers=headers, json=data)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"更新记录失败: {e}")
            return None

    def delete_record(self, object_id, record_id):
        """
        删除记录

        Args:
            object_id (str): 对象ID
            record_id (str): 记录ID
        Returns:
            dict: 删除结果或None
        """
        token = auth_manager.get_token()
        url = f"{settings.CURD_BASE_URL}/{object_id}/records/{record_id}"
        headers = {"Authorization": token}

        try:
            response = requests.delete(url, headers=headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"删除记录失败: {e}")
            return None

    def query_records(self, object_id, query_keys=["_id"]):
        """
        查询记录

        Args:
            object_id (str): 对象ID
            query_keys (list): 查询的字段列表，默认为["_id"]

        Returns:
            dict: 查询结果或None
        """
        token = self.ensure_token_valid()
        if not token:
            return None

        url = f"{settings.CURD_BASE_URL}/{object_id}/records_query"
        headers = {"Authorization": token, "Content-Type": "application/json"}

        # 设置默认查询参数
        query_params = {
            "use_page_token": False,
            "offset": 0,
            "need_total_count": False,
            "filter": {},
            "page_token": "",
            "page_size": 500,
            "query_deleted_record": False,
            "select": query_keys,
        }

        try:
            response = requests.post(url, headers=headers, json=query_params)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"查询记录失败: {e}")
            return None
